package com.lzk.system.service.impl;

import com.lzk.basic.service.impl.BaseServiceImpl;
import com.lzk.system.domain.Role;
import com.lzk.system.mapper.RoleMapper;
import com.lzk.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 重写添加操作
     * 添加role并且添加两个表 role_permisson role_menu
     * @param role
     */
    @Override
    @Transactional
    public void save(Role role) {
       //先保存角色信息
        roleMapper.save(role);
        if(role.getMenus().size() > 0){
            //再保存role_menu
            roleMapper.saveRoleMenu(role.getId(),role.getMenus());
        }
        if(role.getPermissions().size() > 0){
            //最后保存role_permission
            roleMapper.saveRolePermission(role.getId(),role.getPermissions());
        }
    }

    /**
     * 重写更新操作
     * 先清空全部，然后在添加
     * @param role
     */
    @Override
    @Transactional
    public void update(Role role) {
       roleMapper.update(role);

       //先删除
        roleMapper.removeRoleMenu(role.getId());
        roleMapper.removeRolePermission(role.getId());

        //添加
        if(role.getMenus().size() > 0){
            //再保存role_menu
            roleMapper.saveRoleMenu(role.getId(),role.getMenus());
        }
        if(role.getPermissions().size() > 0){
            //最后保存role_permission
            roleMapper.saveRolePermission(role.getId(),role.getPermissions());
        }
    }

    /**
     * 重写删除操作
     * 删除关联的中间表
     * @param id
     */
    @Override
    @Transactional
    public void remove(Long id) {
        //先删除关联表，再删除自己
        roleMapper.removeEmployeeRole(id);
        roleMapper.removeRoleMenu(id);
        roleMapper.removeRolePermission(id);

        // 删除自己
        roleMapper.remove(id);
    }
}
